package br.com.tarlis.persistent.server.mysql;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import br.com.tarlis.core.server.exception.UnexpectedException;
import br.com.tarlis.persistent.client.model.Persistent;
import br.com.tarlis.persistent.server.Factory;

public class MySQLFactory extends Factory {
	
	public static void init() {
		new MySQLFactory();
	}
	
	@Override
	protected <K extends Persistent> void insertImpl(K persistent)
			throws UnexpectedException {
		try {
			List<Field> fields = getFields(persistent);
			
			String sql = "INSERT INTO " + persistent.getClass().getSimpleName() +
						 " (" + fieldsToString(fields) + ") VALUES (" + 
						 parametersCountToString(fields.size()) + ")";
			
			PreparedStatement ps = ((Connection) getActualConnection()
					.getConnection()).prepareStatement(sql);
			
			putParameters(ps, fields);
			
			ps.execute();
			
			//TODO recuperar id;
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw new UnexpectedException(e);
		}
	}

	@Override
	protected <K extends Persistent> void updateImpl(K persistent)
			throws UnexpectedException {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected <K extends Persistent> void deleteImpl(K persistent)
			throws UnexpectedException {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected <K extends Persistent> List<K> listImpl()
			throws UnexpectedException {
		// TODO Auto-generated method stub
		return null;
	}

	private void putParameters(PreparedStatement ps, List<Field> fields) {
		// TODO Auto-generated method stub
		
	}

	private String fieldsToString(List<Field> fields) {
		String sql = "";
		for (int i = 0; i < fields.size(); i++) {
			sql += fields.get(i).getName();
			if (i < (fields.size() - 1)) {
				sql += ",";
			}
		}
		return sql;
	}
	
	private String fieldsToParameterizedString(List<Field> fields) {
		String sql = "";
		for (int i = 0; i < fields.size(); i++) {
			sql += fields.get(i).getName() + "=?";
			if (i < (fields.size() - 1)) {
				sql += ",";
			}
		}
		return sql;
	}
	
	private String parametersCountToString(int parametersCount) {
		String sql = "";
		for (int i = 0; i < parametersCount; i++) {
			sql += "?";
			if (i < (parametersCount - 1)) {
				sql += ",";
			}
		}
		return sql;
	}	

}
